﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;

namespace YTBZ.PUB.COMMON
{
    #region 文件流读取
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class SupFile
    {
        private FileStream fs;
        private BinaryReader br;
        public SupFile(string FilePath)
        {
            fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            br = new BinaryReader(fs);
        }
        /// <summary>
        /// 获取文件字节数组
        /// </summary>
        /// <returns>返回字节数组</returns>
        public Byte[] GetFileByte()
        {
            int fileLength = (int)fs.Length;
            Byte[] FileByte = new Byte[fileLength];
            br.Read(FileByte, 0, fileLength);
            return FileByte;
        }
        /// <summary>
        /// 关闭文件流
        /// </summary>
        public void FileClose()
        {
            fs.Close();
            br.Close();
        }

        /// <summary>
        /// 打开查看文件或下载文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="filePath">完整磁盘路径</param>
        public void OpenDownFile(string fileName, string filePath)
        {
            HttpContext.Current.Response.Clear();
            byte[] fileDate = null;
            fileDate = GetFileByte();

            string fileExt = System.IO.Path.GetExtension(filePath).ToLower().Trim();
            switch (fileExt)
            {
                case ".xls":
                case ".xlsx":
                    HttpContext.Current.Response.ContentType = "application/x-msexcel";
                    break;
                case ".doc":
                case ".docx":
                    HttpContext.Current.Response.ContentType = "application/msword";
                    break;
                case ".gif":
                    HttpContext.Current.Response.ContentType = "image/gif";
                    break;
                case ".jpg":
                    HttpContext.Current.Response.ContentType = "image/jpeg";
                    break;
                case ".bmp":
                    HttpContext.Current.Response.ContentType = "image/bmp";
                    break;
                case ".txt":
                    HttpContext.Current.Response.ContentType = "text/plain";
                    break;
                case ".pdf":
                    HttpContext.Current.Response.ContentType = "application/pdf";
                    break;
                case ".ppt":
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-powerpoint";
                    break;
                case ".zip":
                    HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                    break;
                default:
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    break;
            }

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "%20"));
            // Response.AddHeader("Content-Disposition", " filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "%20"));
            HttpContext.Current.Response.BinaryWrite(fileDate);
            FileClose();
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }

    public static class FileSender
    {
        private const int BufferSize = 1024;

        public static void Send(IPEndPoint ip, string path)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Connect(ip);
            using (FileStream reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                long send = 0L, length = reader.Length;
                sock.Send(BitConverter.GetBytes(length));
                string fileName = Path.GetFileName(path);
                sock.Send(Encoding.Default.GetBytes(fileName));
                Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
                byte[] buffer = new byte[BufferSize];
                int read, sent;
                //断点发送 在这里判断设置reader.Position即可
                while ((read = reader.Read(buffer, 0, BufferSize)) != 0)
                {
                    sent = 0;
                    while ((sent += sock.Send(buffer, sent, read, SocketFlags.None)) < read)
                    {
                        send += (long)sent;
                        //Console.WriteLine("Sent " + send + "/" + length + ".");//进度
                    }
                }
                Console.WriteLine("Send finish.");
            }
        }

        public static void Receive(IPEndPoint ip, string path)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind(ip);
            sock.Listen(1);
            Socket client = sock.Accept();
            byte[] buffer = new byte[BufferSize];
            client.Receive(buffer);
            long receive = 0L, length = BitConverter.ToInt64(buffer, 0);
            string fileName = Encoding.Default.GetString(buffer, 0, client.Receive(buffer));
            Console.WriteLine("Receiveing file:" + fileName + ".Plz wait...");
            using (FileStream writer = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
            {
                int received;
                //断点接受 在这里判断设置writer.Position即可
                while (receive < length)
                {
                    received = client.Receive(buffer);
                    writer.Write(buffer, 0, received);
                    writer.Flush();
                    receive += (long)received;
                    //Console.WriteLine("Received " + receive + "/" + length + ".");//进度
                }
            }
            Console.WriteLine("Receive finish.");
        }
    }

    #endregion
}
